<template>
  <div>
    <!-- 面包屑导航栏 start -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item class="index" :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航栏 end -->
    <!-- 卡片主体区 start -->
    <el-card>
      <!-- 顶部搜索、重置 start -->
      <el-row :gutter="20" v-show="role">
        <!-- 搜索 -->
        <el-col :span="6">
          <el-input placeholder="请输入用户名称" v-model.trim="queryOrderListObj.uname" @change="keyDwon" clearable>
            <el-button slot="append" icon="el-icon-search" title="点击搜索" @click="getOrderList"></el-button>
          </el-input>
        </el-col>
        <!-- 重置 -->
        <el-col :span="2">
          <el-button class="btn-reset" @click="restInput($event)">重置</el-button>
        </el-col>
        <!-- 导出 -->
        <el-col :span="2">
          <el-button class="btn-often" icon="el-icon-upload2" @click="uploadData($event)">导出</el-button>
        </el-col>
      </el-row>
      <!-- 顶部搜索、重置 end -->
      <!-- 表格数据 start -->
      <el-table :data="orderList" height="400px" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="下单用户" prop="uname"></el-table-column>
        <el-table-column label="订单价格(元)" prop="price"></el-table-column>
        <el-table-column label="是否支付" prop="pay_status">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.ispay === 1">已支付</el-tag>
            <el-tag type="danger" v-else>未支付</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否完成" prop="pay_status">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isfinish === 1">已完成</el-tag>
            <el-tag type="danger" v-else>未完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="createtime" width="270" sortable>
          <!-- <template slot-scope="scope">{{ scope.row.create_time | dateFormate }}</template> -->
        </el-table-column>
        <el-table-column label="是否删除" prop="isdelete" v-if="role">
          <template slot-scope="scope">{{ scope.row.isdelete === 1 ? '是' : '否' }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180px" v-if="!role">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-wallet" size="mini" @click="pay(scope.row)" :disabled="scope.row.ispay === 1">支付</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteOrder(scope.row)" :disabled="scope.row.isdelete === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格数据 end -->
      <!-- 分页信息 start -->
      <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="queryOrderListObj.pagenum" :page-sizes="[2, 5, 10, 20]" :page-size="queryOrderListObj.pagesize" layout="sizes, prev, pager, next, jumper,total" :total="total"> </el-pagination>
      <!-- 分页信息 end -->
    </el-card>
    <!-- 卡片主体区 end -->
  </div>
</template>

<script>
import btn from '../utils/btn.js'
export default {
  data() {
    return {
      queryOrderListObj: {
        uname: '',
        pagesize: 5,
        pagenum: 1
      },
      // 订单表格数据
      orderList: [],
      // 订单数据总条数
      total: 0,
      // true为管理员
      role: false,
      user: {},
      // 支付后的余额
      new_balance: 0,
      // 新角色
      new_role: ''
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    getRole() {
      const user = JSON.parse(window.sessionStorage.getItem('user'))
      this.user = user
      if (user.role === '超级管理员' || user.role === '管理员') {
        // 获取所有故障信息
        this.getOrderList()
        this.role = true
      } else {
        // 获取当前用户创建的故障信息
        this.getOrderListById()
      }
      // console.log(this.role ? '不显示' : '显示')
    },
    async getOrderList() {
      const res = await this.$http.get('getAllBackOrder', {
        params: {
          uname: this.queryOrderListObj.uname,
          pageSize: this.queryOrderListObj.pagesize,
          pageNum: this.queryOrderListObj.pagenum
        }
      })
      if (res.data) {
        this.orderList = res.data
        this.orderList.forEach((item) => {
          item.price = item.price.toFixed(2)
        })
        const list = await this.$http.get('getOrder', {
          params: {}
        })
        this.total = list.data.length
      } else {
        this.$message.error('获取订单列表失败！请重新操作！')
      }
    },
    async getOrderListById() {
      const res = await this.$http.get('getBackOrder', {
        params: {
          uid: this.user.id,
          pageSize: this.queryOrderListObj.pagesize,
          pageNum: this.queryOrderListObj.pagenum
        }
      })
      if (res.data) {
        this.orderList = res.data
        this.orderList.forEach((item) => {
          item.price = item.price.toFixed(2)
        })
        const list = await this.$http.get('getAllBackOrderByUid', {
          params: {
            uid: this.user.id
          }
        })
        this.total = list.data.length
      } else {
        this.$message.error('获取订单列表失败！请重新操作！')
      }
    },
    // 重置
    restInput(e) {
      //   取消焦点
      btn.preBtnFocus(e)
      if (this.role) {
        this.queryOrderListObj.uname = ''
        // 刷新表格数据
        this.getOrderList()
      } else {
        this.getOrderListById()
      }
    },
    // 回车搜搜
    keyDwon() {
      this.getOrderList()
    },
    // 监听pagesize改变事件
    pageSizeChange(pageSize) {
      this.queryOrderListObj.pagesize = pageSize
      // 重新分页查询
      if (this.role) {
        this.queryOrderListObj.uname = ''
        // 刷新表格数据
        this.getOrderList()
      } else {
        this.getOrderListById()
      }
    },
    // 监听当前页改变事件
    pageCurrentChange(pageNum) {
      this.queryOrderListObj.pagenum = pageNum
      // 重新分页查询
      if (this.role) {
        this.queryOrderListObj.uname = ''
        // 刷新表格数据
        this.getOrderList()
      } else {
        this.getOrderListById()
      }
    },
    // 支付订单
    async pay(row) {
      const result = await this.$confirm('您需要支付' + row.price + '元是否继续?', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (result === 'confirm') {
        // 查询余额，判断余额是否足够
        const res = await this.$http.get('getUserDetail', {
          params: {
            id: this.user.id
          }
        })
        if (res.data && res.data.balance < row.price) {
          // 提示余额不足，先前往充值余额
          this.$message.error('您的余额不足，请先前往个人中心充值！')
        } else {
          // 余额足够则调用支付接口,提示余额还剩多少,是否降等级
          // console.log('支付......')
          // 判断支付后的角色
          this.new_balance = Number(res.data.balance) - Number(row.price)
          if (this.new_balance < 66) {
            this.new_role = '普通会员'
          } else if (this.new_balance >= 66 && this.new_balance < 88) {
            this.new_role = '高级会员'
          } else if (this.new_balance >= 88) {
            this.new_role = '超级会员'
          }
          // console.log('余额：', this.new_balance, '角色：', this.new_role)
          const data = await this.$http.get('pay', {
            params: {
              role: this.new_role,
              balance: this.new_balance,
              id: this.user.id,
              bid: row.id
            }
          })
          if (data.data === '支付成功！') {
            if (this.user.role === this.new_role) {
              this.$message.success('支付成功！')
            } else {
              this.$message.success('支付成功，但是由于余额不够当前等级，所以等级将降为' + this.new_role + ',若想继续享受当前优惠，请前往充值。')
            }
            // 刷新订单
            this.getOrderListById()
          } else {
            this.$message.error('支付失败！')
          }
        }
      } else {
        this.$message.info('已取消本次支付!')
      }
    },
    // 删除订单
    async deleteOrder(row) {
      const result = await this.$confirm('此操作将永久删除该订单数据, 是否继续?', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (result === 'confirm') {
        if (row.ispay === 0) {
          this.$message.warning('该订单还未完成支付，请先完成支付后再删除！')
        } else {
          const res = await this.$http.get('deleteBackOrder', {
            params: {
              id: row.id
            }
          })
          if (res.data === '删除成功！') {
            this.$message.success('删除成功！')
            this.getOrderListById()
          } else {
            this.$message.error('删除失败，请重新操作！')
          }
        }
      } else {
        this.$message.info('已取消本次删除!')
      }
    },
    // 导出订单
    uploadData(e) {
      btn.preBtnFocus(e)
      window.location.href = 'http://127.0.0.1:8081/uploadOrders'
    }
  }
}
</script>

<style lang="less" scoped></style>
